package com.liao.learntest.job;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author: liaowenqiang
 * @date: 2024/11/16 11:36
 * @description:
 **/
@Slf4j
public class JobService {

    private SettlementJobService settlementJobService;

    public void run(String taskId){
        boolean lockSuccess=false;
        boolean isToRunning=false;
        boolean isBusinessResult=false;
        try{
            //加分布式锁
            if(!(lockSuccess=tryDistributedLock(taskId))){
                return;
            }
            SettlementJobEntity settlementJobEntity = settlementJobService.getById(taskId);
            BusinessSevice businessSevice = SettlementBusinessServiceFactory.getBySettlementStatus(settlementJobEntity.getStatusEnum());

            if(settlementJobEntity==null||businessSevice==null){
                //这种异常不需要重试，因为下一次也不会成功
                return;
            }

            //获取主表的状态，如果任务的状态<主表的状态，直接return

            //更新任务执行状态为执行中
            isToRunning= updateTaskStatusToRunning(taskId);
            if(!isToRunning){
                return;
            }
            //这里可以考虑，记录一下状态变更日志
            try {
                //执行业务逻辑
                isBusinessResult=businessSevice.run(taskId);
            }catch (Exception e){
                log.error("业务逻辑执行异常",e);
                isBusinessResult=false;
            }
            //更新任务执行结果 更新任务表状态，增加执行记录，更新主表状态
            updateTaskStatus(taskId,isBusinessResult);
            //执行成功则发送触发执行下一个阶段的mq消息
            if(isBusinessResult){
                SettlementStatusEnum nextSettlementStatusEnum = SettlementBusinessServiceFactory.getNextSettlementStatusEnum(settlementJobEntity.getStatusEnum());
                if(nextSettlementStatusEnum==null){
                   return;
                }
                SettlementJobEntity nextJobEntity= settlementJobService.getByStatusEnumAndSettlementId(settlementJobEntity.getSettlementId(),nextSettlementStatusEnum);
                //下一个job的执行状态是【已唤醒】再发mq触发。否则等待三方回调
                if(Objects.equals(nextJobEntity.getRunStatusEnum(),RunStatusEnum.AWAKE)){
                    settlementJobService.sendMqMessage(nextJobEntity.getId());
                    log.info("sendMqMessage,result:{}",isBusinessResult);
                }

            }

        }catch (Exception e){

        }finally {
            if (lockSuccess){
                unDistributedLock(taskId);
            }
        }
    }

    private void updateTaskStatus(String taskId, boolean isBusinessResult) {
        //更新当前任务状态
        //更新任务执行记录

        //更新业务表状体信息

    }



    private boolean updateTaskStatusToRunning(String taskId) {
        return true;
    }

    private void unDistributedLock(String taskId) {
        log.info("释放锁");
    }

    private boolean tryDistributedLock(String taskId) {
        return false;
    }

    public static void main(String[] args) {
        JobService jobService=new JobService();
        jobService.run("");
    }
}
